package softtech.apps.autoanswerphonecall;

import java.io.File;
import java.io.IOException;

import softtech.apps.autoanswerphonecall.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class VoiceManagerActivity extends Activity {

	private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
	private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
	private static final String AUDIO_RECORDER_FOLDER = "VoiceMessage";

	
	private MediaPlayer mediaPlayer;
	private MediaRecorder recorder = null;
	private int currentFormat = 0;
	private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
			MediaRecorder.OutputFormat.THREE_GPP };
	private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
			AUDIO_RECORDER_FILE_EXT_3GP };

	Context context = this;

	private File folder;
	private File files[];
	DatabaseHandler db;
	int audio_id;
	int audio_value;
	String filePath = null;
	boolean recording = false;

	AudioManager audioManager;

	int enableVoiceMessageRecord;
	int enableVoiceMessageRecord_id;
	ImageButton btnenableVoiceMessageRecord;

	
	int Maxduration_id;
	int Maxduration;
	private int selected = 0; // change selected to global
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_voice_manager);

		android.app.ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setBackgroundDrawable(new ColorDrawable(Color
				.parseColor("#2ac2d4")));
		actionBar.show();

//		audioManager = (AudioManager) getApplicationContext().getSystemService(
//				Context.AUDIO_SERVICE);
//		audioManager.setMode(AudioManager.MODE_IN_CALL);
//		audioManager.setSpeakerphoneOn(true);

		setButtonHandlers();
		enableButtons(false);
		setFormatButtonCaption();

		db = new DatabaseHandler(this);
		
		String filepath = Environment.getExternalStorageDirectory().getPath();
		folder = new File(filepath, AUDIO_RECORDER_FOLDER);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		files = folder.listFiles();
		
		if(files.length == 0){
			// display dialog here;
			AlertDialogManager adm = new AlertDialogManager();
			adm.showAlertDialog(context, "Notice",
					"Record an audio file if you want to use this mode", true);
		}
		
		Log.d("FILE", "Tong so file =" + files.length);

		Button btnSelect = (Button) findViewById(R.id.btnSelect);
		Config cfgAudio = db.getConfig(4);
		if (!cfgAudio.equals(null) && cfgAudio != null) {
			audio_value = cfgAudio.get_value();
			audio_id = cfgAudio.get_id();

		}

		Config cfgRecordVoiceMessage = db.getConfig(5);
		if (!cfgRecordVoiceMessage.equals(null)
				&& cfgRecordVoiceMessage != null) {
			enableVoiceMessageRecord = cfgRecordVoiceMessage.get_value();
			enableVoiceMessageRecord_id = cfgRecordVoiceMessage.get_id();

		}
		Log.d("VOICE", "Enable voice message =" + enableVoiceMessageRecord);
		
		
		Config cfgMaxduration = db.getConfig(6);
		if (!cfgMaxduration.equals(null)
				&& cfgMaxduration != null) {
			Maxduration = cfgMaxduration.get_value();
			Maxduration_id = cfgMaxduration.get_id();

		}
		Log.d("VOICE", "Max time duration choice =" + Maxduration);
		
		/**
		 * Everything about Button Enable Voice Message Record
		 * */
		btnenableVoiceMessageRecord = (ImageButton) findViewById(R.id.imgEnableVoiceMessageRecord);
		if (enableVoiceMessageRecord == 1) {
			btnenableVoiceMessageRecord.setImageResource(R.drawable.on);
		} else {
			btnenableVoiceMessageRecord.setImageResource(R.drawable.off);
		}
		btnenableVoiceMessageRecord.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Set voice message duration here
				if(enableVoiceMessageRecord == 0){
					viewMaxDuration();
				}

				Config config = new Config();
				config.set_id(enableVoiceMessageRecord_id);
				if (enableVoiceMessageRecord == 1) {
					enableVoiceMessageRecord = 0;
					config.set_value(0);
					btnenableVoiceMessageRecord
							.setImageResource(R.drawable.off);
					Log.d("CLICK", "Off voice message record");
				} else {
					enableVoiceMessageRecord = 1;
					config.set_value(1);
					enableVoiceMessageRecord = 1;
					btnenableVoiceMessageRecord.setImageResource(R.drawable.on);
					Log.d("CLICK", "On voice message record");
				}
				db.updateConfig(config);
			}
		});

		/**
		 * Display audio file name in select button text
		 * 
		 * */

		if (audio_value != -1) {
			if (audio_value <= files.length - 1) {
				String[] separated = files[audio_value].getName().split("/");
				btnSelect.setText(separated[0]);
			} else {
				Config config = new Config();
				config.set_id(audio_id);
				config.set_value(-1);
				db.updateConfig(config);
			}

		}

		Button btnPlay = (Button) findViewById(R.id.btnPlay);
		btnPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				PlayMusic();

			}
		});

	}

	private void viewMaxDuration() {
		AlertDialog.Builder viewDialog = new AlertDialog.Builder(this);

		viewDialog.setTitle("Select maximum time duration");

		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View dialogView = li.inflate(R.layout.max_duration_choice, null);
	
		
		final CharSequence[] choiceList =
		    {"1 minute", "2 minutes" , "3 minutes" , "4 minutes",
				"5 minutes", "10 minutes", "15 minutes","20 minutes"};
		viewDialog.setSingleChoiceItems(
	            choiceList,
	            selected,
	            new DialogInterface.OnClickListener() {
	         
	        @Override
	        public void onClick(
	                DialogInterface dialog,
	                int which) {
	            selected = which;
	        }
	    });
		viewDialog.setView(dialogView);
		viewDialog.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// click ok -> update to database max time duration
					}
				});

		viewDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// set default value
					}
				});
		viewDialog.show();
		
		Spinner spinnercategory = (Spinner) dialogView
				.findViewById(R.id.viewSpin);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.maxdurationchoice, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnercategory.setAdapter(adapter);

		spinnercategory.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View arg1,
					int arg2, long arg3) {
				if(Maxduration != arg2){
					Config config = new Config();
					config.set_id(Maxduration_id);
					config.set_value(arg2);
					db.updateConfig(config);
				}
				Log.d("SPINER","Item selected index = "+arg2);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});

	}
	
	private void setButtonHandlers() {
		((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
		((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
		((Button) findViewById(R.id.btnSelect)).setOnClickListener(btnClick);
		((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
	}

	private void enableButton(int id, boolean isEnable) {
		if (isEnable) {
			((Button) findViewById(id)).setTextColor(Color.WHITE);
		} else {
			((Button) findViewById(id)).setTextColor(Color.rgb(240, 204, 35));
		}
		((Button) findViewById(id)).setEnabled(isEnable);
	}

	private void enableButtons(boolean isRecording) {
		enableButton(R.id.btnStart, !isRecording);
		enableButton(R.id.btnFormat, !isRecording);
		enableButton(R.id.btnStop, isRecording);
		enableButton(R.id.btnPlay, !isRecording);
	}

	private void setFormatButtonCaption() {
		((Button) findViewById(R.id.btnFormat))
				.setText(getString(R.string.audio_format) + " ("
						+ file_exts[currentFormat] + ")");
	}

	private String getFilename() {
		File file = folder;
		if (!file.exists()) {
			file.mkdirs();
		}

		return (file.getAbsolutePath() + "/" + "file-"
				+ System.currentTimeMillis() + file_exts[currentFormat]);

	}

	private void startRecording() {
		/**
		 * Set speaker Off When record
		 * */
		
		AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		
		audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
				audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
		audioManager.setMode(AudioManager.MODE_NORMAL);
		audioManager.setSpeakerphoneOn(false);
		recorder = new MediaRecorder();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(output_formats[currentFormat]);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setOutputFile(getFilename());
		recorder.setOnErrorListener(errorListener);
		recorder.setOnInfoListener(infoListener);

		try {
			recorder.prepare();
			recorder.start();
			recording = true;
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void stopRecording() {
		if (null != recorder && recording) {
			recording = false;
			filePath = getFilename();
			recorder.stop();
			recorder.reset();
			recorder.release();
			recorder = null;
		}
	}

	private void displayFormatDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		String formats[] = { "MPEG 4", "3GPP" };

		builder.setTitle(getString(R.string.choose_format_title))
				.setSingleChoiceItems(formats, currentFormat,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								currentFormat = which;
								setFormatButtonCaption();

								dialog.dismiss();
							}
						}).show();
	}

	private void setFilePathChooseCaption() {
		// String[] separated = files[audio_value].getName().split("/");
		((Button) findViewById(R.id.btnSelect)).setText(files[currentFormat]
				.getName());

		Config config = new Config();
		config.set_id(audio_id);
		config.set_value(currentFormat);

		db.updateConfig(config);
	}

	private void displayAllAudioFiles() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		if (files.length > 0) {
			String temp[] = new String[files.length];
			for (int i = 1; i <= files.length; i++) {
				// temp[i-1] = files[i-1].getAbsolutePath();
				String[] separated = files[i - 1].getName().split("/");
				temp[i - 1] = separated[0];
			}
			// Read all file in folder store in and array
			builder.setTitle(getString(R.string.choose_file_path))
					.setSingleChoiceItems(temp, currentFormat,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									currentFormat = which;

									setFilePathChooseCaption();

									dialog.dismiss();
								}
							}).show();
		} else {
			AlertDialogManager adm = new AlertDialogManager();
			adm.showAlertDialog(context, "Notice",
					"You have no audio record to display", true);
		}

	}

	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
			Toast.makeText(VoiceManagerActivity.this,
					"Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			Toast.makeText(VoiceManagerActivity.this,
					"Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
					.show();
		}
	};

	private void PlayMusic() {
		/**
		 * Play record file with Speaker
		 * */
		
		Config cfgAudio = db.getConfig(4);
		
		AudioManager am = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		am.setMode(AudioManager.STREAM_MUSIC);
		am.setSpeakerphoneOn(true);
		

			am.setStreamVolume(AudioManager.STREAM_MUSIC,
					am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
			
		MediaPlayer mediaPlayer = new MediaPlayer();
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
		    @Override
		    public void onPrepared(MediaPlayer mp) {
		        // Do something. For example: playButton.setEnabled(true);
//		    	mp.start();
		    }
		});
		mediaPlayer.setLooping(false);
		mediaPlayer.setVolume(AudioManager.MODE_IN_CALL, AudioManager.MODE_IN_CALL);
		if (!cfgAudio.equals(null) && cfgAudio.get_value() != -1
				&& cfgAudio.get_value() < files.length) {

			enableButton(R.id.btnStop, false);
			enableButton(R.id.btnStart, false);

			filePath = files[cfgAudio.get_value()].getAbsolutePath().toString();
			try {
				mediaPlayer.setDataSource(filePath);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			try {
				mediaPlayer.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					enableButton(R.id.btnStop, true);
					enableButton(R.id.btnStart, true);
					// TODO Auto-generated method stub
					mp.stop();
					mp.release();
					mp = null;
				}

			});
			mediaPlayer.start();
		} else {
			// reupdate to database
			AlertDialogManager adm = new AlertDialogManager();
			adm.showAlertDialog(context, "Notice",
					"Record an audio file if you want to play it", true);
			Config config = new Config();
			config.set_id(audio_id);
			config.set_value(-1);
			db.updateConfig(config);
			enableButton(R.id.btnStop, true);
			enableButton(R.id.btnStart, true);
			enableButton(R.id.btnPlay, false);
		}

	}

	private View.OnClickListener btnClick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnStart: {
				// Toast.makeText(VoiceManagerActivity.this, "Start Recording",
				// Toast.LENGTH_SHORT).show();

				enableButtons(true);
				startRecording();

				break;
			}
			case R.id.btnStop: {
				// Toast.makeText(VoiceManagerActivity.this, "Stop Recording",
				// Toast.LENGTH_SHORT).show();
				enableButtons(false);
				stopRecording();

				break;
			}
			case R.id.btnSelect: {
				displayAllAudioFiles();
				break;
			}

			case R.id.btnFormat: {
				displayFormatDialog();

				break;
			}
			}
		}
	};
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		default:
		}

		return super.onOptionsItemSelected(item);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu items for use in the action bar
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.voice_manager, menu);
		return super.onCreateOptionsMenu(menu);
	}
}